/*
 * @Description: description
 * @version: 0.1
 * @Author: youhuimin
 * @Date: 2021-08-20 13:19:03
 * @LastEditors: youhuimin
 * @LastEditTime: 2021-08-20 14:30:54
 * @FilePath: \xdeas-user-web\src\components\roomTree\treeTools.js
 */
export default {
  // 深度优先遍历的递归实现
  treeForeach:function (tree, func,childParam = 'children') {
    tree.forEach(data => {
      func(data)
      data[childParam] && this.treeForeach(data[childParam], func,childParam) // 遍历子树
    })
  },
  // 列表转树
  listToTree :function(list,childParam = 'children') {
    let info = list.reduce((map, node) => (map[node.id] = node, node[childParam] = [], map), {})
    return list.filter(node => {
      info[node.parentId] && info[node.parentId][childParam].push(node)
      return !node.parentId
    })
  },
  // 树结构筛选
   treeFilter:function (tree, func,childParam = 'children') {
    // 使用map复制一下节点，避免修改到原树
    return tree.map(node => ({ ...node })).filter(node => {
      node[childParam] = node[childParam] && this.treeFilter(node[childParam], func,childParam)
      return func(node) || (node[childParam] && node[childParam].length)
    })
  },
  // 查找节点路径
  treeFindPath:function(tree, func, path = [],childParam = 'children') {
    if (!tree) return []
    for (const data of tree) {
      path.push(data.id)
      if (func(data)) return path
      if (data[childParam]) {
        const findChildren = this.treeFindPath(data[childParam], func, path,childParam)
        if (findChildren.length) return findChildren
      }
      path.pop()
    }
    return []
  },
  // 查找节点
  treeFind: function(tree, func, childParam = 'children') {
    for (const data of tree) {
      if (func(data)) return data
      if (data[childParam]) {
        const res = this.treeFind(data[childParam], func,childParam)
        if (res) return res
      }
    }
    return null
  },
}